﻿
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using WeiXinAPIs.Models;
//
using WeiXinAPIs.Libs;

namespace WeiXinAPIs
{
    /// <summary>
    /// 微信基础API
    /// </summary>
    public abstract class BaseAPI
    {
        /// <summary>
        /// 是否是企业号
        /// </summary>
        public bool IsQY
        {
            get
            {
                bool result = true;
                if (!Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsQY"]))
                {
                    result = false;
                }
                return result;
            }
        }

        #region 配置回调URL及密钥
        /// <summary>
        /// 非企业号为appid,企业号为corpid
        /// </summary>
        public string WeiXinID
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["WeiXinID"].ToString();
            }
        }
        /// <summary>
        /// 开发者凭据
        /// </summary>
        public string Secret
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["Secret"].ToString();
            }
        }


        #endregion

        #region AES加密解密
        /// <summary>
        /// Token
        /// </summary>
        public string Token
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["Token"].ToString();
            }
        }
        /// <summary>
        /// AES密钥
        /// </summary>
        public string EncodingAESKey
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["EncodingAESKey"].ToString();
            }
        }
        #endregion


        #region 域名
        public string DomainUrl
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["DomainUrl"].ToString();
            }
        }
        #endregion

        #region 获取AccessToken

        /// <summary>
        /// 获取Token
        /// </summary>
        public AccessToken AccessToken
        {
            get
            {
                if (CurrentAccessToken.ExpiresTime == null || CurrentAccessToken.ExpiresTime <= DateTime.Now)
                {
                    CurrentAccessToken.AccessToken = this.Get<AccessToken>(new InterFaceUrlAPI(IsQY, WeiXinID, Secret).AccessTokenUrl);
                    CurrentAccessToken.ExpiresTime = DateTime.Now.AddSeconds(CurrentAccessToken.AccessToken.expires_in);
                }
                return CurrentAccessToken.AccessToken;
            }
        }
        #endregion

        #region AES加密
        /// <summary>
        /// 微信中消息回密解密处理类
        /// </summary>
        protected class Cryptography
        {
            public static UInt32 HostToNetworkOrder(UInt32 inval)
            {
                UInt32 outval = 0;
                for (int i = 0; i < 4; i++)
                    outval = (outval << 8) + ((inval >> (i * 8)) & 255);
                return outval;
            }

            public static Int32 HostToNetworkOrder(Int32 inval)
            {
                Int32 outval = 0;
                for (int i = 0; i < 4; i++)
                    outval = (outval << 8) + ((inval >> (i * 8)) & 255);
                return outval;
            }
            /// <summary>
            /// 解密方法
            /// </summary>
            /// <param name="Input">密文</param>
            /// <param name="EncodingAESKey"></param>
            /// <returns></returns>
            /// 
            public static string AES_decrypt(String Input, string EncodingAESKey, ref string corpid)
            {
                byte[] Key;
                Key = Convert.FromBase64String(EncodingAESKey + "=");
                byte[] Iv = new byte[16];
                Array.Copy(Key, Iv, 16);
                byte[] btmpMsg = AES_decrypt(Input, Iv, Key);

                int len = BitConverter.ToInt32(btmpMsg, 16);
                len = IPAddress.NetworkToHostOrder(len);


                byte[] bMsg = new byte[len];
                byte[] bCorpid = new byte[btmpMsg.Length - 20 - len];
                Array.Copy(btmpMsg, 20, bMsg, 0, len);
                Array.Copy(btmpMsg, 20 + len, bCorpid, 0, btmpMsg.Length - 20 - len);
                string oriMsg = Encoding.UTF8.GetString(bMsg);
                corpid = Encoding.UTF8.GetString(bCorpid);
                return oriMsg;
            }

            public static String AES_encrypt(String Input, string EncodingAESKey, string corpid)
            {
                byte[] Key;
                Key = Convert.FromBase64String(EncodingAESKey + "=");
                byte[] Iv = new byte[16];
                Array.Copy(Key, Iv, 16);
                string Randcode = CreateRandCode(16);
                byte[] bRand = Encoding.UTF8.GetBytes(Randcode);
                byte[] bCorpid = Encoding.UTF8.GetBytes(corpid);
                byte[] btmpMsg = Encoding.UTF8.GetBytes(Input);
                byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length));
                byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bCorpid.Length + btmpMsg.Length];

                Array.Copy(bRand, bMsg, bRand.Length);
                Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length);
                Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length);
                Array.Copy(bCorpid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bCorpid.Length);

                return AES_encrypt(bMsg, Iv, Key);

            }
            private static string CreateRandCode(int codeLen)
            {
                string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
                if (codeLen == 0)
                {
                    codeLen = 16;
                }
                string[] arr = codeSerial.Split(',');
                string code = "";
                int randValue = -1;
                Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
                for (int i = 0; i < codeLen; i++)
                {
                    randValue = rand.Next(0, arr.Length - 1);
                    code += arr[randValue];
                }
                return code;
            }

            private static String AES_encrypt(String Input, byte[] Iv, byte[] Key)
            {
                var aes = new RijndaelManaged();
                //秘钥的大小，以位为单位
                aes.KeySize = 256;
                //支持的块大小
                aes.BlockSize = 128;
                //填充模式
                aes.Padding = PaddingMode.PKCS7;
                aes.Mode = CipherMode.CBC;
                aes.Key = Key;
                aes.IV = Iv;
                var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
                byte[] xBuff = null;

                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                    {
                        byte[] xXml = Encoding.UTF8.GetBytes(Input);
                        cs.Write(xXml, 0, xXml.Length);
                    }
                    xBuff = ms.ToArray();
                }
                String Output = Convert.ToBase64String(xBuff);
                return Output;
            }

            private static String AES_encrypt(byte[] Input, byte[] Iv, byte[] Key)
            {
                var aes = new RijndaelManaged();
                //秘钥的大小，以位为单位
                aes.KeySize = 256;
                //支持的块大小
                aes.BlockSize = 128;
                //填充模式
                //aes.Padding = PaddingMode.PKCS7;
                aes.Padding = PaddingMode.None;
                aes.Mode = CipherMode.CBC;
                aes.Key = Key;
                aes.IV = Iv;
                var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
                byte[] xBuff = null;

                #region 自己进行PKCS7补位，用系统自己带的不行
                byte[] msg = new byte[Input.Length + 32 - Input.Length % 32];
                Array.Copy(Input, msg, Input.Length);
                byte[] pad = KCS7Encoder(Input.Length);
                Array.Copy(pad, 0, msg, Input.Length, pad.Length);
                #endregion

                #region 注释的也是一种方法，效果一样
                //ICryptoTransform transform = aes.CreateEncryptor();
                //byte[] xBuff = transform.TransformFinalBlock(msg, 0, msg.Length);
                #endregion

                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                    {
                        cs.Write(msg, 0, msg.Length);
                    }
                    xBuff = ms.ToArray();
                }

                String Output = Convert.ToBase64String(xBuff);
                return Output;
            }

            private static byte[] KCS7Encoder(int text_length)
            {
                int block_size = 32;
                // 计算需要填充的位数
                int amount_to_pad = block_size - (text_length % block_size);
                if (amount_to_pad == 0)
                {
                    amount_to_pad = block_size;
                }
                // 获得补位所用的字符
                char pad_chr = chr(amount_to_pad);
                string tmp = "";
                for (int index = 0; index < amount_to_pad; index++)
                {
                    tmp += pad_chr;
                }
                return Encoding.UTF8.GetBytes(tmp);
            }
            /**
             * 将数字转化成ASCII码对应的字符，用于对明文进行补码
             * 
             * @param a 需要转化的数字
             * @return 转化得到的字符
             */
            static char chr(int a)
            {

                byte target = (byte)(a & 0xFF);
                return (char)target;
            }
            private static byte[] AES_decrypt(String Input, byte[] Iv, byte[] Key)
            {
                RijndaelManaged aes = new RijndaelManaged();
                aes.KeySize = 256;
                aes.BlockSize = 128;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.None;
                aes.Key = Key;
                aes.IV = Iv;
                var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
                byte[] xBuff = null;
                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
                    {
                        byte[] xXml = Convert.FromBase64String(Input);
                        byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32];
                        Array.Copy(xXml, msg, xXml.Length);
                        cs.Write(xXml, 0, xXml.Length);
                    }
                    xBuff = decode2(ms.ToArray());
                }
                return xBuff;
            }
            private static byte[] decode2(byte[] decrypted)
            {
                int pad = (int)decrypted[decrypted.Length - 1];
                if (pad < 1 || pad > 32)
                {
                    pad = 0;
                }
                byte[] res = new byte[decrypted.Length - pad];
                Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
                return res;
            }
        }
        #endregion



        /// <summary>
        /// 字典排序
        /// </summary>
        public class DictionarySort : System.Collections.IComparer
        {
            public int Compare(object oLeft, object oRight)
            {
                string sLeft = oLeft as string;
                string sRight = oRight as string;
                int iLeftLength = sLeft.Length;
                int iRightLength = sRight.Length;
                int index = 0;
                while (index < iLeftLength && index < iRightLength)
                {
                    if (sLeft[index] < sRight[index])
                        return -1;
                    else if (sLeft[index] > sRight[index])
                        return 1;
                    else
                        index++;
                }
                return iLeftLength - iRightLength;
            }
        }


        /// <summary>
        /// 将时间数字转换成日期
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        protected static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        public static void SaveImage(string url, string fileName)
        {
            using (WebClient c = new WebClient())
            {
                c.DownloadFile(url, fileName);
            }

        }
        /// <summary>
        /// 输出日志
        /// </summary>
        /// <param name="message"></param>
        public static void Log(string message)
        {
            try
            {
                var fileName = System.Web.HttpContext.Current.Server.MapPath("/WeiXinLogs/") + "WXLog" + DateTime.Now.ToString("yyyyMMdd") +".txt";
                message = "***   " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", System.Globalization.CultureInfo.InvariantCulture) + "   ***" + Environment.NewLine + message;
                using (var sw= System.IO.File.AppendText(fileName))
                {
                    sw.WriteLine(message);
                };
            }
            catch { }
        }

    }

    #region 回复消息码枚举
    enum WXBizMsgCryptErrorCode
    {
        WXBizMsgCrypt_OK = 0,
        WXBizMsgCrypt_ValidateSignature_Error = -40001,
        WXBizMsgCrypt_ParseXml_Error = -40002,
        WXBizMsgCrypt_ComputeSignature_Error = -40003,
        WXBizMsgCrypt_IllegalAesKey = -40004,
        WXBizMsgCrypt_ValidateCorpid_Error = -40005,
        WXBizMsgCrypt_EncryptAES_Error = -40006,
        WXBizMsgCrypt_DecryptAES_Error = -40007,
        WXBizMsgCrypt_IllegalBuffer = -40008,
        WXBizMsgCrypt_EncodeBase64_Error = -40009,
        WXBizMsgCrypt_DecodeBase64_Error = -40010
    };
    #endregion

}
